package ck.mmd.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import ck.mmd.bean.Adopt;
import ck.mmd.bean.AdoptOrder;
import ck.mmd.bean.News;
import ck.mmd.bean.PetType;
import ck.mmd.bean.Remark;
import ck.mmd.bean.User;
import ck.mmd.dao.AdoptDao;
import ck.mmd.dao.AdoptOrderDao;
import ck.mmd.dao.PetTypeDao;
import ck.mmd.dao.RemarkDao;
import ck.mmd.dao.UserDao;
import ck.mmd.util.JsonUtil;
import ck.mmd.util.StoreUtil;
import ck.mmd.util.StringUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class AdoptAction extends ActionSupport  implements SessionAware{
	private static final long serialVersionUID = 1L;
	private Adopt adopt;
	private AdoptDao adao = new AdoptDao();
	private UserDao userdao = new UserDao();
	private RemarkDao remarkdao = new RemarkDao();
	private PetTypeDao petdao = new PetTypeDao();
	private AdoptOrderDao aodao = new AdoptOrderDao();
	HttpServletRequest request = ServletActionContext.getRequest();
	HttpServletResponse response = ServletActionContext.getResponse();
	
	public Adopt getModel() {
		if(adopt == null){
			return adopt = new Adopt();
		}
		return adopt;
	}
	
	/**
	 * 发布领养信息
	 * @return
	 * @throws IOException
	 */
	public String add_adopt() throws IOException{
		User newuser = new User();
		newuser = (User)ActionContext.getContext().getSession().get("user");
		Adopt newadopt = new Adopt();
		String error;
		if(newuser == null){
			PrintWriter out = response.getWriter();
			out.print("<script language='JavaScript'> alert('你未登录!');  " +
					" location.href='"+request.getContextPath()+"/';</script>");
			return null;
		}else{
			String title = request.getParameter("title");
			String dogtype_id = request.getParameter("dogtype_id");
			String address = request.getParameter("address");
			String petname = request.getParameter("petname");
			String petage = request.getParameter("petage");
			String petsex = request.getParameter("petsex");
			String petcolor = request.getParameter("petcolor");
			String html = request.getParameter("html");
			String content = request.getParameter("content");
			
			newadopt.setStatus(1);
			newadopt.setUptime(new Date());
			newadopt.setSenduser_id(newuser.getId());
			newadopt.setTitle(title);
			newadopt.setDogtype_id(dogtype_id);
			newadopt.setAddress(address);
			newadopt.setPetname(petname);
			newadopt.setPetage(petage);
			newadopt.setPetsex(petsex);
			newadopt.setPetcolor(petcolor);
			newadopt.setHtml(html);
			newadopt.setContent(content);
			newadopt.setId(StringUtils.getUUID());
			newadopt.setLooknum(StoreUtil.getRandom(50, 200));
			newadopt.setReallooknum(0);
			newadopt.setRemarknum(0);
			newadopt.setIssend(0);
			newadopt.setIsfortrue(0);
			//添加领养信息
			adao.addAdopt(newadopt);
			Adopt adoptdemo = adao.findAdoptById(newadopt.getId());
			
			if(adoptdemo == null){
				error = "1";
			}else{
				//更新用户领养信息数量
				userdao.updateAdopt_num(newuser.getAdopt_num()+1,newuser.getId());
				error = "0";
			}
			response.getWriter().print(error);
		}
		return null;
	}
	
	/**
	 * 我发布的领养单
	 * @return
	 * @throws IOException 
	 */
	public String my_allSendAdopts() throws IOException{
		ActionContext context = ActionContext.getContext();
		User newuser = new User();
		newuser = (User)ActionContext.getContext().getSession().get("user");
		if(newuser == null){
			PrintWriter out = response.getWriter();
			out.print("<script language='JavaScript'> alert('你未登录!');  " +
					" location.href='"+request.getContextPath()+"/';</script>");
			return null;
		}else{
			//获取所有的领养
			List<Adopt> adoptlist = new ArrayList<Adopt>();
			adoptlist = adao.findSendAdoptsById(newuser.getId());
			if(adoptlist.size() <= 0){
				context.put("isnull", 0);
				context.put("msg", "没有发布了的领养信息...");
			}else{
				Iterator<Adopt> it =  adoptlist.iterator();
				List<Adopt> list = new ArrayList<Adopt>();
				while(it.hasNext()){
					Adopt adopt = it.next();
					adopt.setPettype(petdao.findPetTypeById(adopt.getDogtype_id()));
					adopt.setSenduser(userdao.findUserById(adopt.getSenduser_id()));
					list.add(adopt);
				}
				context.put("isnull", 1);
				context.put("list", list);
			}
		}
		return "my_allSendAdopts";
	}
	
	/**
	 * 我接收的领养单
	 * @return
	 * @throws IOException 
	 */
	public String my_allRecvAdopts() throws IOException{
		ActionContext context = ActionContext.getContext();
		User newuser = new User();
		newuser = (User)ActionContext.getContext().getSession().get("user");
		if(newuser == null){
			PrintWriter out = response.getWriter();
			out.print("<script language='JavaScript'> alert('你未登录!');  " +
					" location.href='"+request.getContextPath()+"/';</script>");
			return null;
		}else{
			//获取所有的新闻
			List<Adopt> adoptlist = new ArrayList<Adopt>();
			adoptlist = adao.findRecvAdoptsById(newuser.getId());
			if(adoptlist.size() <= 0){
				context.put("isnull", 0);
				context.put("msg", "没有接收了的领养信息...");
			}else{
				Iterator<Adopt> it =  adoptlist.iterator();
				List<Adopt> list = new ArrayList<Adopt>();
				while(it.hasNext()){
					Adopt adopt = it.next();
					adopt.setPettype(petdao.findPetTypeById(adopt.getDogtype_id()));
					adopt.setSenduser(userdao.findUserById(adopt.getRecvuser_id()));
					list.add(adopt);
				}
				context.put("isnull", 1);
				context.put("list", list);
			}
		}
		return "my_allRecvAdopts";
	}
	
	/**
	 * 删除领养
	 * @return
	 * @throws IOException
	 */
	public String deleteAdopt() throws IOException{
		User newuser = new User();
		newuser = (User)ActionContext.getContext().getSession().get("user");
		String error = "0";
		if(newuser == null){
			PrintWriter out = response.getWriter();
			out.print("<script language='JavaScript'> alert('你未登录!');  " +
					" location.href='"+request.getContextPath()+"/';</script>");
			return null;
		}else{
			String id = request.getParameter("id");
			if(id.equals("") || id.equals(null)){
				error = "1";
			}else{
				adao.deleteAdoptById(id);
				Adopt adoptdemo = adao.findAdoptById(id);
				if(adoptdemo.getStatus() == 1){
					error = "1";
				}else{
					error = "0";
				}
			}
			response.getWriter().print(error);
		}
		return null;
	}
	
	/**
	 * 最新领养
	 * @return
	 * @throws IOException
	 */
	public String zxadopt() throws IOException{
		int size = Integer.parseInt(request.getParameter("size"));
		List<Adopt> list = adao.findAdoptBySort(size);
		Iterator<Adopt> it =  list.iterator();
		List<Adopt> listdemo = new ArrayList<Adopt>();
		while(it.hasNext()){
			Adopt adopt = it.next();
			adopt.setUptimestr(adopt.getUptime()+"");
			adopt.setPettype(petdao.findPetTypeById(adopt.getDogtype_id()));
			adopt.setSenduser(userdao.findUserById(adopt.getSenduser_id()));
			listdemo.add(adopt);
		}
		String liststr = JsonUtil.list2json(listdemo);
		response.getWriter().print(liststr);
		return null;
	}
	
	/**
	 * 领养详情
	 * @return
	 */
	public String detail(){
		ActionContext context = ActionContext.getContext();
		String id = request.getParameter("key");
		Adopt adopt = new Adopt();
		adopt = adao.findAdoptById(id);
		adopt.setPettype(petdao.findPetTypeById(adopt.getDogtype_id()));
		adopt.setSenduser(userdao.findUserById(adopt.getSenduser_id()));
		
		//查询评论
		List<Remark> remarklist = new ArrayList<Remark>();
		remarklist = remarkdao.findRemarksByUId(adopt.getId());
		if(remarklist.size() <= 0){
			context.put("size","0");
		}else{
			Iterator<Remark> it =  remarklist.iterator();
			List<Remark> remarklistdemo = new ArrayList<Remark>();
			while(it.hasNext()){
				Remark remark = it.next();
				remark.setUser(userdao.findUserById(remark.getUser_id()));
				remarklistdemo.add(remark);
			}
			context.put("size","1");
			context.put("remarklist",remarklistdemo);
		}
		context.put("adopt",adopt);
		return "detail";
	}
	
	public String lookAdopt_edit(){
		ActionContext context = ActionContext.getContext();
		String id = request.getParameter("key");
		Adopt adopt = new Adopt();
		adopt = adao.findAdoptById(id);
		adopt.setPettype(petdao.findPetTypeById(adopt.getDogtype_id()));
		adopt.setSenduser(userdao.findUserById(adopt.getSenduser_id()));
		adopt.setRecvuser(userdao.findUserById(adopt.getRecvuser_id()));
		context.put("adopt",adopt);
		return "lookAdopt_edit";
	}
	
	public String lookAdopt(){
		ActionContext context = ActionContext.getContext();
		String id = request.getParameter("key");
		Adopt adopt = new Adopt();
		adopt = adao.findAdoptById(id);
		adopt.setPettype(petdao.findPetTypeById(adopt.getDogtype_id()));
		adopt.setSenduser(userdao.findUserById(adopt.getSenduser_id()));
		adopt.setRecvuser(userdao.findUserById(adopt.getRecvuser_id()));
		context.put("adopt",adopt);
		return "lookAdopt";
	}
	
	/**
	 * 确认申请  生成领养单
	 * @return
	 * @throws IOException
	 */
	public String fortrue_adopt() throws IOException{
		String id = request.getParameter("id");
		String error = "0";
		if(!id.equals("")){
			Adopt adopt = adao.findAdoptById(id);
			if(adopt == null){
				error = "1";
			}else{
				//修改领养已被领养
				adao.updateIsfortrue(id,1);
				//修改领养没有被申请
				adao.updateIsSend(id,0);
				//生成订单
				String orderid = StringUtils.getUUID();
				String sendid = adopt.getSenduser_id();
				String recvid = adopt.getRecvuser_id();
				AdoptOrder order = new AdoptOrder();
				order.setId(orderid);
				order.setSenduser_id(sendid);
				order.setRecvuser_id(recvid);;
				order.setAdopt_id(id);
				order.setTime(new Date());
				//添加领养单
				aodao.addAdoptOrder(order);
				error = "0";
			}
		}
		response.getWriter().print(error);
		return null;
	}
	
	public String send_adopt() throws IOException{
		User newuser = new User();
		newuser = (User)ActionContext.getContext().getSession().get("user");
		String error = "0";
		String id = request.getParameter("id");
		if(newuser == null){
			error = "2";
		}else{
			if(!id.equals("")){
				Adopt adopt = adao.findAdoptById(id);
				if(adopt == null){
					error = "1";
				}else{
					//修改领养被申请
					adao.updateIsSend(id,1);
					//修改认领人为该用户
					adao.adaoupdateRecvUser(id,newuser.getId());
					error = "0";
				}
			}else{
				error = "1";
			}
		}
		response.getWriter().print(error);
		return null;
	}
	
	public String execute(){
		return "success";
	}
	
	public void setSession(Map<String, Object> arg0) {
		
	}
}
